package com.qyhl.webtv.module_circle.utils.itemview;

import android.Manifest;
import android.app.Activity;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.style.ClickableSpan;
import android.text.style.TextAppearanceSpan;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.like.LikeButton;
import com.like.OnLikeListener;
import com.qyhl.webtv.basiclib.utils.DateUtils;
import com.qyhl.webtv.basiclib.utils.MPermissionUtils;
import com.qyhl.webtv.basiclib.utils.SpanUtils;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.dialog.OtherDialog;
import com.qyhl.webtv.basiclib.utils.glide.GlideCircleTransform;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.circle.CircleHomeBean;
import com.qyhl.webtv.commonlib.service.UserService;
import com.qyhl.webtv.commonlib.utils.MShareBoard;
import com.qyhl.webtv.commonlib.utils.eventbus.BusFactory;
import com.qyhl.webtv.commonlib.utils.eventbus.Event;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.commonlib.utils.view.MyListView;
import com.qyhl.webtv.commonlib.utils.view.NoScrollLinkMovementMethod;
import com.qyhl.webtv.commonlib.utils.view.expandableView.text.ExpandableTextView;
import com.qyhl.webtv.module_circle.R;
import com.qyhl.webtv.module_circle.utils.LinkMovementClickMethod;
import com.zhy.adapter.abslistview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ItemViewDelegate;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import es.dmoral.toasty.Toasty;

import static com.qyhl.webtv.commonlib.utils.view.video.emptyvideo.EmptyControlVideoActivity.IntentKey_VideoCover;
import static com.qyhl.webtv.commonlib.utils.view.video.emptyvideo.EmptyControlVideoActivity.IntentKey_VideoUrl;


/**
 * Created by qyhl on 2018/1/19.
 * 圈子视频item
 */

public class ItemVideoView implements ItemViewDelegate<CircleHomeBean>, ItemViewContract.ItemView {
    private Activity activity;
    private ItemViewPresenter mPresenter;
    private RequestOptions apply;
    private boolean isHome;
    private boolean isSingle;

    public ItemVideoView(Activity activity) {
        this.activity = activity;
        mPresenter = new ItemViewPresenter(this);
        apply = new RequestOptions().error(R.drawable.video_list_portrait_default).placeholder(R.drawable.video_list_portrait_default);
    }

    public ItemVideoView(Activity activity, boolean isHome) {
        this.activity = activity;
        mPresenter = new ItemViewPresenter(this);
        this.apply = new RequestOptions().error(R.drawable.video_list_portrait_default).placeholder(R.drawable.video_list_portrait_default);
        this.isHome = isHome;
    }

    public ItemVideoView(Activity activity, boolean isHome, boolean isSingle) {
        this.activity = activity;
        mPresenter = new ItemViewPresenter(this);
        this.apply = new RequestOptions().error(R.drawable.video_list_portrait_default).placeholder(R.drawable.video_list_portrait_default);
        this.isHome = isHome;
        this.isSingle = isSingle;
    }

    @Override
    public int getItemViewLayoutId() {
        return R.layout.circle_item_circle_video;
    }

    @Override
    public boolean isForViewType(CircleHomeBean item, int position) {
        if (item.getType() == 3) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void convert(ViewHolder holder, final CircleHomeBean bean, final int position) {
        //头像
        ImageView headIcon = holder.getView(R.id.head_icon);
        Glide.with(activity)
                .load(bean.getUser().getLogo())
                .apply(new RequestOptions().error(R.drawable.comment_head_default).placeholder(R.drawable.comment_head_default)
                        .optionalTransform(new GlideCircleTransform(activity)))
                .into(headIcon);

        headIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("dstusername", bean.getUser().getUsername());
                RouterManager.router(ARouterPathConstant.CIRCLE_USER, bundle);
            }
        });

        //昵称
        TextView nickName = holder.getView(R.id.nickname);
        nickName.setText(bean.getUser().getNickName());

        //发布时间
        TextView time = holder.getView(R.id.publish_date);
        time.setText(DateUtils.mTranslateDate(bean.getTopicDate()));

        //举报
        TextView complain = holder.getView(R.id.complain);
        String userName = CommonUtils.getInstance().getUserName();
        if (bean.getUser().getUsername().equals(userName)) {
            complain.setVisibility(View.GONE);
        } else {
            complain.setVisibility(View.VISIBLE);
        }
        complain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                    @Override
                    public void login(boolean isLogin) {
                        if (isLogin) {
                            Bundle bundle = new Bundle();
                            bundle.putString("type", "1");
                            bundle.putString("id", bean.getId() + "");
                            RouterManager.router(ARouterPathConstant.CIRCLE_COMPLAIN, bundle);

                        } else {
                            Toasty.normal(activity, "尚未登录或登录已失效！").show();
                            RouterManager.routerLogin(activity, 0);
                        }
                    }

                    @Override
                    public void error(String s) {

                    }
                });

                CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                    @Override
                    public void login(boolean isLogin) {
                        if (isLogin) {
                            Bundle bundle = new Bundle();
                            bundle.putString("type", "1");
                            bundle.putString("id", bean.getId() + "");
                            RouterManager.router(ARouterPathConstant.CIRCLE_COMPLAIN, bundle);
                        } else {
                            Toasty.normal(activity, "尚未登录或登录已失效！").show();
                            RouterManager.routerLogin(activity, 0);
                        }
                    }

                    @Override
                    public void error(String s) {

                    }
                });
            }
        });

        //地址
        TextView location = holder.getView(R.id.location);
        if (StringUtils.isNotEmpty(bean.getPosition())) {
            location.setVisibility(View.VISIBLE);
            location.setText(bean.getPosition());
        } else {
            location.setVisibility(View.GONE);
        }

        //分享
        TextView share = holder.getView(R.id.share_btn);
        share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!bean.isLocal) {
                    MPermissionUtils.requestPermissionsResult((Activity) activity, 1, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, new MPermissionUtils.OnPermissionListener() {
                        @Override
                        public void onPermissionGranted() {
                            MShareBoard shareBoard = new MShareBoard(activity, bean.getId() + "", "来自" + bean.getUser().getNickName() + "的朋友圈", bean.getVideoThumb(), bean.getContent(), CommonUtils.getInstance().getBannerId(), 15);
                            shareBoard.showPopupWindow();
                        }

                        @Override
                        public void onPermissionDenied() {
                            MPermissionUtils.showTipsDialog(activity);
                        }
                    });
                }
            }
        });

        //评论
        final TextView comment = holder.getView(R.id.comment);
        if (bean.getPostCount() > 0) {
            comment.setText(bean.getPostCount() + "");
        } else {
            comment.setText("评论");
        }
        //评论点击事件
        comment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!bean.isLocal) {

                    CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                        @Override
                        public void login(boolean isLogin) {
                            if (isLogin) {
                                BusFactory.getBus().post(new Event.CommentEvent(bean, position, -1));
                            } else {
                                Toasty.normal(activity, "尚未登录或登录失效！").show();
                                RouterManager.routerLogin(activity, 0);
                            }
                        }

                        @Override
                        public void error(String s) {

                        }
                    });

                }
            }
        });

        //点赞状态设置
        final LikeButton likeBtn = holder.getView(R.id.like_btn);
        TextView likeNum = holder.getView(R.id.like_num);

        if (bean.getLoveCount() < 1) {
            likeNum.setText("点赞");
        } else {
            likeNum.setText(bean.getLoveCount() + "");
        }

        if (bean.isLove()) {
            likeBtn.setLiked(true);
        } else {
            likeBtn.setLiked(false);
        }

        likeBtn.setTag(bean);
        likeBtn.setTag(R.id.like_num, likeNum);
        //关注监听
        likeBtn.setOnLikeListener(new OnLikeListener() {
            @Override
            public void liked(final LikeButton likeButton) {
                CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                    @Override
                    public void login(boolean isLogin) {
                        if (isLogin) {
                            TextView num = (TextView) likeButton.getTag(R.id.like_num);
                            CircleHomeBean bean = (CircleHomeBean) likeButton.getTag();
                            bean.setLoveCount(bean.getLoveCount() + 1);
                            setChecked(num, likeBtn, bean.getLoveCount());
                            mPresenter.doLove(bean.getId() + "", bean);
                        } else {
                            likeBtn.setLiked(false);
                            Toasty.normal(activity, "尚未登录或登录已失效！", Toast.LENGTH_SHORT).show();
                            RouterManager.routerLogin(activity, 300);
                        }
                    }

                    @Override
                    public void error(String s) {

                    }
                });

            }

            @Override
            public void unLiked(final LikeButton likeButton) {
                CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                    @Override
                    public void login(boolean isLogin) {
                        if (isLogin) {
                            TextView num = (TextView) likeButton.getTag(R.id.like_num);
                            CircleHomeBean bean = (CircleHomeBean) likeButton.getTag();
                            bean.setLoveCount(bean.getLoveCount() - 1);
                            setNormal(num, likeBtn, bean.getLoveCount());
                            mPresenter.undoLove(bean.getId() + "", bean);
                        } else {
                            likeBtn.setLiked(true);
                            Toasty.normal(activity, "尚未登录或登录已失效！", Toast.LENGTH_SHORT).show();
                            RouterManager.routerLogin(activity, 300);
                        }
                    }

                    @Override
                    public void error(String s) {

                    }
                });
            }
        });

        ImageView videoCover = holder.getView(R.id.video_cover);
        ViewGroup.LayoutParams params = videoCover.getLayoutParams();
        if (StringUtils.isNotEmpty(bean.getVideoHeight()) && StringUtils.isNotEmpty(bean.getVideoWidth())) {
            if (Integer.parseInt(bean.getVideoWidth()) > Integer.parseInt(bean.getVideoHeight())) {
                params.width = Integer.parseInt(bean.getVideoWidth()) > 600 ? 600 : Integer.parseInt(bean.getVideoWidth());
                params.height = params.width * 9 / 16;
            } else {
                params.height = Integer.parseInt(bean.getVideoHeight()) > 600 ? 600 : Integer.parseInt(bean.getVideoHeight());
                params.width = params.height * 9 / 16;
            }
        } else {
            params.height = 600;
            params.width = params.height * 9 / 16;
        }

        videoCover.setLayoutParams(params);
        Glide.with(activity).load(bean.getVideoThumb()).apply(apply).into(videoCover);
//        if (!TextUtils.isEmpty(trim)) {
//            int width = Integer.parseInt(bean.getVideoWidth().trim());
//            int height = Integer.parseInt(bean.getVideoHeight().trim());
//            if (width > height) {
//                params.width = width > 600 ? 600 : width;
//                params.height = params.width * 9 / 16;
//            } else {
//                params.height = height > 600 ? 600 : height;
//                params.width = params.height * 9 / 16;
//            }
//            videoCover.setLayoutParams(params);
//            Glide.with(activity).load(bean.getVideoThumb()).apply(apply).into(videoCover);
//        }

        RelativeLayout videoLayout = holder.getView(R.id.video_layout);
        videoLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString(IntentKey_VideoUrl, bean.getVideo());
                bundle.putString(IntentKey_VideoCover, bean.getVideoThumb());
                RouterManager.router(ARouterPathConstant.VIDEO_EMPTY_CONTROL, bundle);
            }
        });

        //设置精彩评论
        final List<CircleHomeBean.PostList> beanList = new ArrayList<>();
        MyListView listView = holder.getView(R.id.my_listview);
        final CommonAdapter<CircleHomeBean.PostList> commonAdapter = new CommonAdapter<CircleHomeBean.PostList>(activity, R.layout.circle_item_circle_reply_txt, beanList) {
            @Override
            protected void convert(com.zhy.adapter.abslistview.ViewHolder viewHolder, final CircleHomeBean.PostList item, final int pos) {
                TextView reply = viewHolder.getView(R.id.reply);
                String name = item.getUser().getNickName();
                String content = ": " + item.getContent();
                SpanUtils spanUtils = new SpanUtils(activity);
                //1评论 2回复
                if (item.getType() == 1) {
                    spanUtils.append(name).setSpans(new TextAppearanceSpan(activity, R.style.circle_comment_name)).setClickSpan(new ClickableSpan() {
                        @Override
                        public void onClick(View widget) {
                            Bundle bundle = new Bundle();
                            bundle.putString("dstusername", item.getUser().getUsername());
                            RouterManager.router(ARouterPathConstant.CIRCLE_USER, bundle);
                        }

                        @Override
                        public void updateDrawState(TextPaint ds) {
                            ds.setUnderlineText(false);//取消下划线
                        }
                    }).append(content).setSpans(new TextAppearanceSpan(activity, R.style.circle_comment_content)).setClickSpan(new ClickableSpan() {
                        @Override
                        public void onClick(View widget) {
                            String userName = CommonUtils.getInstance().getUserName();
                            if (!bean.getPostList().get(pos).getUser().getUsername().equals(userName)) {
                                BusFactory.getBus().post(new Event.CommentEvent(bean, position, pos));
                            }
                        }

                        @Override
                        public void updateDrawState(TextPaint ds) {
                            ds.setUnderlineText(false);//取消下划线
                        }
                    });
                } else {
                    String dstname = item.getReply().getNickName();

                    spanUtils.append(name).setSpans(new TextAppearanceSpan(activity, R.style.circle_comment_name)).setClickSpan(new ClickableSpan() {
                        @Override
                        public void onClick(View widget) {
                            Bundle bundle = new Bundle();
                            bundle.putString("dstusername", item.getUser().getUsername());
                            RouterManager.router(ARouterPathConstant.CIRCLE_USER, bundle);
                        }

                        @Override
                        public void updateDrawState(TextPaint ds) {
                            ds.setUnderlineText(false);//取消下划线
                        }
                    })
                            .append("回复").setSpans(new TextAppearanceSpan(activity, R.style.circle_comment_content))
                            .append(dstname).setSpans(new TextAppearanceSpan(activity, R.style.circle_comment_name)).setClickSpan(new ClickableSpan() {
                        @Override
                        public void onClick(View widget) {
                            Bundle bundle = new Bundle();
                            bundle.putString("dstusername", item.getReply().getUsername());
                            RouterManager.router(ARouterPathConstant.CIRCLE_USER, bundle);
                        }

                        @Override
                        public void updateDrawState(TextPaint ds) {
                            ds.setUnderlineText(false);//取消下划线
                        }
                    }).append(content).setSpans(new TextAppearanceSpan(activity, R.style.circle_comment_content)).setClickSpan(new ClickableSpan() {
                        @Override
                        public void onClick(View widget) {
                            String userName = CommonUtils.getInstance().getUserName();
                            if (!bean.getPostList().get(pos).getUser().getUsername().equals(userName)) {
                                BusFactory.getBus().post(new Event.CommentEvent(bean, position, pos));
                            }
                        }

                        @Override
                        public void updateDrawState(TextPaint ds) {
                            ds.setUnderlineText(false);//取消下划线
                        }
                    });
                }
                reply.setText(spanUtils.create());
                reply.setMovementMethod(LinkMovementClickMethod.getInstance());//开始响应点击事件
                reply.setFocusable(false);
            }
        };

        listView.setAdapter(commonAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
                String userName = CommonUtils.getInstance().getUserName();
                if (!bean.getPostList().get(pos).getUser().getUsername().equals(userName)) {
                    BusFactory.getBus().post(new Event.CommentEvent(bean, position, pos));
                } else if (bean.getPostList().get(pos).getUser().getUsername().equals(bean.getUser().getUsername())) {
                    BusFactory.getBus().post(new Event.CommentEvent(bean, position, -1));
                }
            }
        });

        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                String userName = CommonUtils.getInstance().getUserName();
                if (beanList.get(position).getUser().getUsername().equals(userName)) {
                    new OtherDialog.Builder(activity)
                            .setContentView(R.layout.circle_layout_dialog_delete)
                            .setGravity(Gravity.BOTTOM)
                            .setOnClickListener(R.id.delete, new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                                        @Override
                                        public void login(boolean isLogin) {
                                            if (isLogin) {
                                                mPresenter.deleteComment(beanList.get(position).getId() + "", beanList, commonAdapter);
                                            } else {
                                                Toasty.normal(activity, "尚未登录或登录已失效！").show();
                                                RouterManager.routerLogin(activity, 0);
                                            }
                                        }

                                        @Override
                                        public void error(String s) {

                                        }
                                    });

                                }
                            }).show();
                } else {
                    new OtherDialog.Builder(activity)
                            .setContentView(R.layout.circle_layout_dialog_other)
                            .setGravity(Gravity.BOTTOM)
                            .setOnClickListener(R.id.complain, new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                                        @Override
                                        public void login(boolean isLogin) {
                                            if (isLogin) {
                                                Bundle bundle = new Bundle();
                                                bundle.putString("type", "2");
                                                bundle.putString("id", bean.getPostList().get(position).getId() + "");
                                                RouterManager.router(ARouterPathConstant.CIRCLE_COMPLAIN, bundle);
                                            } else {
                                                Toasty.normal(activity, "尚未登录或登录已失效！").show();
                                                RouterManager.routerLogin(activity, 0);
                                            }
                                        }

                                        @Override
                                        public void error(String s) {

                                        }
                                    });

                                }
                            }).show();
                }
                return true;
            }
        });

        if (bean.getPostList() != null) {
            beanList.clear();
            beanList.addAll(bean.getPostList());
            commonAdapter.notifyDataSetChanged();
        }


        //设置内容
        ExpandableTextView mContent = holder.getView(R.id.content);
        String content = bean.getContent();
        //多文本样式工具类
        SpanUtils spanUtils = new SpanUtils(activity);
        if (bean.getPriority() != 1) {
            spanUtils.appendImage(R.drawable.circle_top, SpanUtils.ALIGN_CENTER).appendSpace(2);
        }
        for (int i = 0; i < bean.getTagList().size(); i++) {
            String tag = "#" + bean.getTagList().get(i).getName() + "#";
            final int finalI = i;
            spanUtils.append(tag).setSpans(new TextAppearanceSpan(activity, R.style.circle_content_tag)).setClickSpan(new ClickableSpan() {
                @Override
                public void onClick(View widget) {
                    //跳转到话题--------------------------------------
                    if (!isSingle) {
                        Bundle bundle = new Bundle();
                        bundle.putString("id", bean.getTagList().get(finalI).getId() + "");
                        RouterManager.router(ARouterPathConstant.CIRCLE_TOPIC, bundle);
                    }
                }

                @Override
                public void updateDrawState(TextPaint ds) {
                    ds.setUnderlineText(false);//取消下划线
                }
            });
        }

        spanUtils.append(content).setSpans(new TextAppearanceSpan(activity, R.style.circle_content_txt)).setClickSpan(new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                //跳转到详情
                Bundle bundle = new Bundle();
                bundle.putString("id", bean.getId() + "");
                RouterManager.router(ARouterPathConstant.CIRCLE_DETAIL, bundle);
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                ds.setUnderlineText(false);//取消下划线
            }
        });

        SpannableStringBuilder spString = spanUtils.create();

        if (StringUtils.isNotEmpty(spString.toString())) {
            mContent.setVisibility(View.VISIBLE);
            mContent.setText(spString, position);
            mContent.getTextView().setOnTouchListener(new NoScrollLinkMovementMethod());
        } else {
            mContent.setVisibility(View.GONE);
        }
    }

    /**
     * 设置点赞状态
     */
    private void setChecked(TextView likeNum, LikeButton likeBtn, int follow) {
        likeNum.setText(StringUtils.transformNum(follow + ""));
        likeBtn.setLiked(true);
    }

    /**
     * 设置未点赞状态
     */
    private void setNormal(TextView likeNum, LikeButton likeBtn, int follow) {
        if (follow > 0) {
            likeNum.setText(StringUtils.transformNum(follow + ""));
        } else {
            likeNum.setText("点赞");
        }
        likeBtn.setLiked(false);
    }

    /**
     * 点赞成功
     */
    @Override
    public void doLoveSuccess(CircleHomeBean bean) {
        if (!isHome) {
            BusFactory.getBus().postSticky(new Event.praiseRefreshEvent(bean.getId(), 1));
        }
    }

//    /**
//     * 点赞失败
//     *
//     * @param msg
//     */
//    @Override
//    public void doLoveError(String msg, TextView likeBtn) {
//        likeBtn.setEnabled(true);
//        Toasty.error(activity, msg).show();
//    }

    /**
     * 取消点赞成功
     */
    @Override
    public void undoLoveSuccess(CircleHomeBean bean) {
        if (!isHome) {
            BusFactory.getBus().postSticky(new Event.praiseRefreshEvent(bean.getId(), 0));
        }
    }

//    /**
//     * 取消点赞失败
//     *
//     * @param msg
//     */
//    @Override
//    public void undoLoveError(String msg, TextView likeBtn) {
//        likeBtn.setEnabled(true);
//        Toasty.error(activity, msg).show();
//    }

    @Override
    public void deleteSuccess(List<CircleHomeBean.PostList> beanList, CommonAdapter commonAdapter) {
        commonAdapter.notifyDataSetChanged();
    }

    @Override
    public void deleteError(String msg) {
        Toasty.normal(activity, msg).show();
    }
}
